﻿using System;
using System.Data;
using System.Linq;
using QueryBuilder;
using FlexCel.Core;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using FlexCel.Render;
using System.Collections;
using InfoSoftGlobal;


namespace TVC.Modules.Ddb
{
    public class MyGadget
    {
        //DataTable _dt = null;
        public string sErr = "";
        //string _FilterPara = "FilterPara";
        string _ValueFormData = "";
        string _Path = "";
        public MainForm MainForm { get; set; }
        public string Path
        {
            get { return _Path; }
            set { _Path = value; }
        }
        readonly Dictionary<string, object> _params = new Dictionary<string, object>();
        BindingList<MyChart> _charts = new BindingList<MyChart>();

        public BindingList<MyChart> Charts
        {
            get { return _charts; }
            set { _charts = value; }
        }
        private Dictionary<string, object> Params
        {
            get
            {
                return _params;
            }
        }
        DTO.LIST_GADGETInfo _info = new DTO.LIST_GADGETInfo();

        public DTO.LIST_GADGETInfo Info
        {
            get { return _info; }
            set { _info = value; }
        }
        //String link = VWGContext.Current.HttpContext.Request.PhysicalApplicationPath;

        public ExcelFile XlsPrint { get; set; }

        public ExcelFile Xls { get; set; }

        public string ValueFormData
        {
            get { return _ValueFormData; }
            set { _ValueFormData = value; }
        }
        public int ID
        {
            get { return _info.ID; }
        }

        public MyGadget(DTO.LIST_GADGETInfo info, String valueformdata, MainForm form)
        {
            _info = info;
            _ValueFormData = valueformdata;
            SetParameters(_ValueFormData);
            MainForm = form;
        }
        public void SetParameters(string paramString)
        {
            if (paramString != "")
            {
                _params.Clear();
                String[] value = paramString.Split('&');
                if (value.Length > 0)
                {
                    for (int i = 0; i < value.Length; i++)
                    {
                        String[] temp = value[i].Split('=');
                        if (temp.Length >= 2)
                        {
                            if (_params.ContainsKey(temp[0]))
                            {
                                if (temp[0].Length + 1 < value[i].Length)
                                    _params[temp[0]] = value[i].Substring(temp[0].Length + 1);
                            }
                            else
                            {
                                _params.Add(temp[0], value[i].Substring(temp[0].Length + 1));
                            }
                        }
                    }


                }
            }
        }
        public void Init()
        {
            Report.ReportGenerator rg = null;
            using (DataSet ds = new DataSet())
            {
                if (_info.ReportTmp != "" || _info.QDCode != "")
                {
                    String namereport = "";
                    if (_info.ReportTmp != "")
                        namereport = "DB_" + _info.ReportTmp;
                    else
                        namereport = _info.QDCode;
                    CoreCommonControl.SetConnection(MainForm.ReportConnectString);
                    try
                    {
                        if (_info.QDCode != "")
                        {
                            //         _info.ReportTmp = _info.QDCode;
                            SQLBuilder sqlBuilder = SQLBuilder.LoadSQLBuilderFromDataBase(_info.QDCode, MainForm.DB, "");
                            foreach (Filter f in sqlBuilder.Filters)
                            {
                                foreach (KeyValuePair<string, object> it in _params)
                                {
                                    f.ValueFrom = f.ValueFrom.Replace(String.Format("{{{0}}}", it.Key), it.Value.ToString());
                                    f.ValueTo = f.ValueTo.Replace(String.Format("{{{0}}}", it.Key), it.Value.ToString());
                                }
                            }
                            rg = new Report.ReportGenerator(sqlBuilder, namereport, "", MainForm.AppConnectString, MainForm.ServerPath + "ReportTemplate\\", MainForm.ServerPath + "Report\\", "");
                        }
                        else
                        {
                            rg = new Report.ReportGenerator(ds, namereport, MainForm.DB, MainForm.AppConnectString, MainForm.ServerPath + "ReportTemplate\\", MainForm.ServerPath + "Report\\", "");
                        }
                        rg.ValueList = _params;
                        Xls = rg.CreateReport();
                    }
                    catch (Exception e)
                    {
                        sErr = e.Message;
                    }
                }
            }


        }
        private string ExportHTML(string path, string code)
        {
            String filename = String.Format("{0}{1}.htm", path, code);
            //TextWriter file = new StringWriter(); ;
            if (Xls == null)
                Init();
            try
            {
                FlexCelHtmlExport html = new FlexCelHtmlExport();

                html.Workbook = Xls;
                THtmlExtraInfo inf = new THtmlExtraInfo();

                String js = @"function getVWGcontrolID() {
                            var objCurNode = this.window;

                            if (objCurNode.frames) {
                                if (objCurNode.frames.frameElement) {
                                    if (objCurNode.frames.frameElement.id) {
                                        var strID = objCurNode.frames.frameElement.id;
                                        if (strID.substring(0, 4) == 'TRG_')
                                            return strID.substring(4);
                                    }
                                }
                            }

                            return 'undefined';
                        }";

                html.ExtraInfo.HeadStart = new string[] { "<script src='Resources.Gizmox.WebGUI.Forms.Skins.CommonSkin.Interfaces.js.wgx' type='text/javascript'></script>", "<script language='javascript' type='text/javascript'>",js,
                    "function tavico_link(cmd,args) {"," var strID = getVWGcontrolID() ;var objEvent = VWG.Events.CreateEvent(strID, 'TaViCo_Link');","VWG.Events.SetEventAttribute(objEvent, cmd, args);","VWG.Events.RaiseEvents();}","</script>",
                    "<script language='JavaScript' src='/FusionCharts/FusionCharts.js'></script>"};

                html.AllowOverwritingFiles = true;
                html.SavedImagesFormat = THtmlImageFormat.Png;
                html.Export(filename, "images", String.Format("css\\{0}.css", code));


                return filename;
            }
            catch
            {
                return "";
            }
        }
        public void Reload()
        {
            _charts.Clear();
            Xls = null;
            XlsPrint = null;
            BUS.LIST_CHARTControl ctrchart = new BUS.LIST_CHARTControl();
            using (DataTable dt = ctrchart.Get_ByIDGadget(MainForm.DB, Info.ID, ref sErr))
            {
                foreach (DataRow row in dt.Rows)
                {
                    MyChart chart = new MyChart() { ChartInf = new DTO.LIST_CHARTInfo(row) };
                    Charts.Add(chart);
                }
            }


            //Init();
        }

        public string LoadGadget(ref String pathfile, string pathHTML, string htmlHandle)
        {
            String namereport = "";
            if (_info.ReportTmp != "")
                namereport = "DB_" + _info.ReportTmp;
            else
                namereport = _info.QDCode;
            namereport = namereport + DateTime.Now.ToString("yyMMddhhmmssffff");
            if (pathfile == "")
                pathfile = ExportHTML(_Path, namereport);
            string content = "";
            if (!File.Exists(pathfile))
                return "";
            using (StreamReader sr = new StreamReader(pathfile))
            {
                content = sr.ReadToEnd();
            }
            content = content.Replace("{0}", htmlHandle);
            content = ReplaceCodeChart(content, _charts, Xls);
            try
            {
                using (FileStream fs = File.Create(pathfile))
                {
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                        sw.Write(content);
                    }
                }
                String[] s = pathfile.Split('\\');
                return String.Format("/{0}/{1}", pathHTML, s[s.Length - 1]);
            }
            catch (Exception e)
            {
                return e.Message;
            }

        }
        #region Chart
        String global = "";
        readonly ArrayList clv2 = new ArrayList();
        readonly ArrayList lv1 = new ArrayList();
        readonly ArrayList lv2 = new ArrayList();
        readonly ArrayList lv3 = new ArrayList();
        readonly ArrayList lv4 = new ArrayList();

        readonly ArrayList dlv1 = new ArrayList();
        readonly ArrayList dlv2 = new ArrayList();
        readonly ArrayList dlv3 = new ArrayList();
        readonly ArrayList dlv4 = new ArrayList();
        public String ReplaceCodeChart(String content, BindingList<MyChart> dt, ExcelFile xls)
        {
            foreach (MyChart row in dt)
            {
                String codechart = GetCodeChart(xls, row.ChartInf);

                if (content.Contains(row.PositionReplace.Trim()))
                    content = content.Replace(row.PositionReplace.Trim(), codechart);
            }

            return content;
        }
        public String GetCodeChart(ExcelFile _xlsFile, DTO.LIST_CHARTInfo inf)
        {
            String _dataxml = "";
            int XF = 0;

            int currentSheet = _xlsFile.ActiveSheet;
            int indexSheet = _xlsFile.GetSheetIndex(inf.SheetChart.Trim());
            _xlsFile.ActiveSheet = indexSheet;
            String _codechart = "";
            TXlsNamedRange range = _xlsFile.GetNamedRange(inf.NameRange.Trim(), indexSheet);
            if (range != null)
            {
                string attribute = "";
                _dataxml = "<chart>";

                attribute += " formatNumberScale='0' ";

                TXlsNamedRange rangeCaption = _xlsFile.GetNamedRange(inf.CaptionRange.Trim(), indexSheet);
                if (rangeCaption != null && rangeCaption.IsOneCell)
                {
                    string caption = _xlsFile.GetCellValue(indexSheet, rangeCaption.Top, rangeCaption.Left, ref XF) == null ? "" : _xlsFile.GetCellValue(indexSheet, rangeCaption.Top, rangeCaption.Left, ref XF).ToString();
                    if (caption.Trim() != "")
                        attribute += String.Format(" caption='{0}'", XmlEncoder.Decode(caption));
                }

                TXlsNamedRange rangesubCaption = _xlsFile.GetNamedRange(inf.SubCaptionRange.Trim(), indexSheet);
                if (rangesubCaption != null && rangesubCaption.IsOneCell)
                {
                    string caption = _xlsFile.GetCellValue(indexSheet, rangesubCaption.Top, rangesubCaption.Left, ref XF) == null ? "" : _xlsFile.GetCellValue(indexSheet, rangesubCaption.Top, rangesubCaption.Left, ref XF).ToString();
                    if (caption.Trim() != "")
                        attribute += String.Format(" subCaption='{0}'", XmlEncoder.Decode(caption));
                }

                TXlsNamedRange rangValue = _xlsFile.GetNamedRange("value", indexSheet);
                String boolvalue = "";
                if (rangValue != null && rangValue.IsOneCell)
                {
                    boolvalue = _xlsFile.GetCellValue(indexSheet, rangValue.Top, rangValue.Left, ref XF) == null ? "" : _xlsFile.GetCellValue(indexSheet, rangValue.Top, rangValue.Left, ref XF).ToString();
                }
                if (boolvalue != "X")
                {
                    attribute += " showValues='0' ";
                }

                //     attribute += " useRoundEdges='1' ";
                TXlsNamedRange linkchart = _xlsFile.GetNamedRange("linkchart", indexSheet);
                string valuelink = "";
                if (linkchart != null && linkchart.IsOneCell)
                {
                    valuelink = _xlsFile.GetCellValue(indexSheet, linkchart.Top, linkchart.Left, ref XF) == null ? "" : _xlsFile.GetCellValue(indexSheet, linkchart.Top, linkchart.Left, ref XF).ToString();
                }
                if (valuelink != "" && valuelink == "X") // link chart
                {
                    string namex = _xlsFile.GetCellValue(indexSheet, range.Top, range.Left, ref XF) == null ? "" : _xlsFile.GetCellValue(indexSheet, range.Top, range.Left, ref XF).ToString();
                    string namey = _xlsFile.GetCellValue(indexSheet, range.Top, range.Left + 1, ref XF) == null ? "" : _xlsFile.GetCellValue(indexSheet, range.Top, range.Left + 1, ref XF).ToString();
                    if (namex != "")
                        attribute += String.Format(" xAxisName='{0}'", XmlEncoder.Decode(namex));
                    if (namey != "")
                        attribute += String.Format(" yAxisName='{0}'", XmlEncoder.Decode(namey));
                    int icurr = 0;
                    global = "";
                    _dataxml += GetXMLLinkChart(_xlsFile, indexSheet, inf.NameRange.Trim(), 0, 1, ref XF, ref icurr);
                    //        string[] s = _dataxml.Split(new string[] { "<*>", "<*><*>" }, StringSplitOptions.None);
                    //    _dataxml = _dataxml.Insert(_dataxml.IndexOf("<linkeddata") - 1, global);

                }

                else // not link chart
                {
                    if (range.ColCount == 2)
                    {
                        string namex = _xlsFile.GetCellValue(indexSheet, range.Top, range.Left, ref XF) == null ? "" : _xlsFile.GetCellValue(indexSheet, range.Top, range.Left, ref XF).ToString();
                        string namey = _xlsFile.GetCellValue(indexSheet, range.Top, range.Left + 1, ref XF) == null ? "" : _xlsFile.GetCellValue(indexSheet, range.Top, range.Left + 1, ref XF).ToString();
                        if (namex != "")
                            attribute += String.Format(" xAxisName='{0}'", XmlEncoder.Decode(namex));
                        if (namey != "")
                            attribute += String.Format(" yAxisName='{0}'", XmlEncoder.Decode(namey));

                        for (int i = 1; i < range.RowCount - 1; i++)
                        {
                            string comment = _xlsFile.GetComment(range.Top + i, range.Left + 1).ToString();
                            if (comment.Contains("TT_XLB_EB"))
                            {
                                comment = "tavico://ANALYSERUI?tag=" + StringToBase64(comment);
                                String temp1 = String.Format("tavico_link('LinkInfo','{0}')", comment);
                                temp1 = temp1.Replace("'", "&quot;");
                                comment = "javascript:" + temp1;

                                comment = String.Format("link='{0}'", comment);
                            }
                            else
                                comment = "";
                            const string icolor = "";
                            //icolor = _xlsFile.GetColorPalette(_xlsFile.GetCellVisibleFormatDef(range.Top + i, range.Left + 1).Font.Color.Index).Name;

                            //icolor = " color='" + icolor + "'";
                            string name = "";
                            //if (boolvalue == "X")
                            name = _xlsFile.GetCellValue(indexSheet, range.Top + i, range.Left, ref XF) == null ? "" : _xlsFile.GetCellValue(indexSheet, range.Top + i, range.Left, ref XF).ToString();

                            string value = _xlsFile.GetCellValue(indexSheet, range.Top + i, range.Left + 1, ref XF) == null ? "" : _xlsFile.GetCellValue(indexSheet, range.Top + i, range.Left + 1, ref XF).ToString();
                            string temp = String.Format("<set label ='{0}' value='{1}' {2}{3} />", XmlEncoder.Decode(name), value, comment, icolor);
                            _dataxml += temp;
                        }
                    }
                    else if (range.ColCount > 2)
                    {
                        TXlsNamedRange rangeRowColumn = _xlsFile.GetNamedRange("rowcolumn", indexSheet);
                        String rowcolumn = "";

                        if (rangeRowColumn != null && rangeRowColumn.IsOneCell)
                        {
                            rowcolumn = _xlsFile.GetCellValue(indexSheet, rangeRowColumn.Top, rangeRowColumn.Left, ref XF) == null ? "" : _xlsFile.GetCellValue(indexSheet, rangeRowColumn.Top, rangeRowColumn.Left, ref XF).ToString();
                        }
                        #region DataLable
                        _dataxml += "<categories>";

                        if (rowcolumn == "X")
                        {
                            for (int i = 1; i < range.ColCount; i++)
                            {
                                //<category label='Austria' /> 
                                string value = _xlsFile.GetCellValue(indexSheet, range.Top, range.Left + i, ref XF) == null ? "" : _xlsFile.GetCellValue(indexSheet, range.Top, range.Left + i, ref XF).ToString();
                                string temp = String.Format("<category label ='{0}'/>", value);
                                _dataxml += temp;
                            }
                        }
                        else
                        {
                            for (int i = 1; i < range.RowCount - 1; i++)
                            {
                                //<category label='Austria' /> 
                                string value = _xlsFile.GetCellValue(indexSheet, range.Top + i, range.Left, ref XF) == null ? "" : _xlsFile.GetCellValue(indexSheet, range.Top + i, range.Left, ref XF).ToString();
                                string temp = String.Format("<category label ='{0}'/>", value);
                                _dataxml += temp;
                            }
                        }

                        _dataxml += "</categories>";
                        #endregion

                        if (rowcolumn == "X")
                        {
                            for (int i = 1; i < range.RowCount - 1; i++)
                            {
                                //<dataset seriesName='1997' color='F6BD0F' showValues='0'>
                                string seriesName = _xlsFile.GetCellValue(indexSheet, range.Top + i, range.Left, ref XF) == null ? "" : _xlsFile.GetCellValue(indexSheet, range.Top + i, range.Left, ref XF).ToString();
                                const String showvalue = "";
                                //if (boolvalue == "X")
                                //    showvalue = "showValues='0'";
                                string renderas = _xlsFile.GetCellValue(indexSheet, range.Top + i, range.Left - 1, ref XF) == null ? "" : _xlsFile.GetCellValue(indexSheet, range.Top + i, range.Left - 1, ref XF).ToString();
                                if (renderas != "")
                                    _dataxml += String.Format("<dataset seriesName='{0}' {1} renderAs='{2}'>", XmlEncoder.Encode(seriesName), showvalue, renderas.Trim());
                                else
                                    _dataxml += String.Format("<dataset seriesName='{0}' {1}>", XmlEncoder.Encode(seriesName), showvalue);

                                for (int j = 1; j < range.ColCount; j++)
                                {
                                    //<set label="Item A" value="4" />
                                    string comment = _xlsFile.GetComment(range.Top + i, range.Left + j).ToString();
                                    if (comment.Contains("TT_XLB_EB"))
                                    {
                                        comment = "tavico://ANALYSERUI?tag=" + StringToBase64(comment);
                                        String temp1 = String.Format("tavico_link('LinkInfo','{0}')", comment);
                                        temp1 = temp1.Replace("'", "&quot;");
                                        comment = "javascript:" + temp1;

                                        comment = String.Format("link='{0}'", comment);
                                    }
                                    else
                                        comment = "";

                                    //comment = XmlEncoder.Encode(comment);
                                    //comment = XmlEncoder.Decode(comment);f
                                    string icolor = "";
                                    //if (_xlsFile.GetCellVisibleFormatDef(range.Top + i, range.Left + j).Font.Color.IsAutomatic)
                                    //    icolor = _xlsFile.GetCellVisibleFormatDef(range.Top + i, range.Left + j).Font.Color.RGB.ToString();
                                    //else
                                    //    icolor = _xlsFile.GetColorPalette(_xlsFile.GetCellVisibleFormatDef(range.Top + j, range.Left + i).Font.Color.Index).Name;

                                    icolor = String.Format(" color='{0}'", icolor);
                                    string value = _xlsFile.GetCellValue(indexSheet, range.Top + i, range.Left + j, ref XF) == null ? "" : _xlsFile.GetCellValue(indexSheet, range.Top + i, range.Left + j, ref XF).ToString();
                                    string temp = String.Format("<set value='{0}' {1}{2} />", XmlEncoder.Decode(value), comment, icolor);
                                    _dataxml += temp;
                                }
                                _dataxml += "</dataset>";
                            }
                        }
                        else
                        {
                            for (int i = 1; i < range.ColCount; i++)
                            {
                                //<dataset seriesName='1997' color='F6BD0F' showValues='0'>
                                string seriesName = _xlsFile.GetCellValue(indexSheet, range.Top, range.Left + i, ref XF) == null ? "" : _xlsFile.GetCellValue(indexSheet, range.Top, range.Left + i, ref XF).ToString();
                                const String showvalue = "";
                                //if (boolvalue == "X")
                                //    showvalue = "showValues='0'";
                                string renderas = _xlsFile.GetCellValue(indexSheet, range.Top - 1, range.Left + i, ref XF) == null ? "" : _xlsFile.GetCellValue(indexSheet, range.Top - 1, range.Left + i, ref XF).ToString();
                                if (renderas != "")
                                    _dataxml += String.Format("<dataset seriesName='{0}' {1} renderAs='{2}'>", XmlEncoder.Encode(seriesName), showvalue, renderas.Trim());
                                else
                                    _dataxml += String.Format("<dataset seriesName='{0}' {1}>", XmlEncoder.Encode(seriesName), showvalue);

                                //       _dataxml += "<dataset seriesName='" + XmlEncoder.Encode(seriesName) + "' " + showvalue + ">";

                                for (int j = 1; j < range.RowCount - 1; j++)
                                {
                                    //<set label="Item A" value="4" />
                                    string comment = _xlsFile.GetComment(range.Top + j, range.Left + i).ToString();
                                    if (comment.Contains("TT_XLB_EB"))
                                    {
                                        comment = "tavico://ANALYSERUI?tag=" + StringToBase64(comment);
                                        String temp1 = String.Format("tavico_link('LinkInfo','{0}')", comment);
                                        temp1 = temp1.Replace("'", "&quot;");
                                        comment = "javascript:" + temp1;

                                        comment = String.Format("link='{0}'", comment);
                                    }
                                    else
                                        comment = "";

                                    //comment = XmlEncoder.Encode(comment);
                                    //comment = XmlEncoder.Decode(comment);f
                                    string icolor = "";
                                    //if (_xlsFile.GetCellVisibleFormatDef(range.Top + j, range.Left + i).Font.Color.IsAutomatic)
                                    //    icolor = _xlsFile.GetCellVisibleFormatDef(range.Top + j, range.Left + i).Font.Color.RGB.ToString();
                                    //else
                                    //    icolor = _xlsFile.GetColorPalette(_xlsFile.GetCellVisibleFormatDef(range.Top + j, range.Left + i).Font.Color.Index).Name;

                                    icolor = String.Format(" color='{0}'", icolor);
                                    string value = _xlsFile.GetCellValue(indexSheet, range.Top + j, range.Left + i, ref XF) == null ? "" : _xlsFile.GetCellValue(indexSheet, range.Top + j, range.Left + i, ref XF).ToString();
                                    string temp = String.Format("<set value='{0}' {1}{2} />", XmlEncoder.Decode(value), comment, icolor);
                                    _dataxml += temp;
                                }
                                _dataxml += "</dataset>";
                            }
                        }
                    }
                }

                _xlsFile.ActiveSheet = currentSheet;
                _dataxml = _dataxml.Insert(_dataxml.IndexOf("<chart>") + 6, attribute);
                _dataxml += "</chart>";
                //          _dataxml = "<chart caption='Country Comparison' showLabels='1' showvalues='0' decimals='0' numberPrefix='$'><categories><category label='Austria' /><category label='Brazil' /><category label='France' /><category label='Germany' /><category label='USA' /></categories><dataset seriesName='1996' color='AFD8F8' showValues='0'><set value='25601.34' /><set value='20148.82' /><set value='17372.76' /><set value='35407.15' /><set value='38105.68' /></dataset><dataset seriesName='1997' color='F6BD0F' showValues='0'><set value='57401.85' /><set value='41941.19' /><set value='45263.37' /><<set value='114845.27' /></dataset><dataset seriesName='1998' color='8BBA00' showValues='0'><set value='45000.65' /><set value='44835.76' /><set value='18722.18' /><set value='77557.31' /><set value='92633.68' /></dataset></chart>";

                if (valuelink != "" && valuelink == "X") // link chart
                {
                    TXlsNamedRange splitchart = _xlsFile.GetNamedRange("splitchart", indexSheet);
                    TXlsNamedRange listsplitchart = _xlsFile.GetNamedRange("listsplitchart", indexSheet);
                    String split = "";
                    String listsplit = "";
                    String rootchart = "";
                    if (splitchart != null && splitchart.IsOneCell)
                    {
                        split = _xlsFile.GetCellValue(indexSheet, splitchart.Top, splitchart.Left, ref XF) == null ? "" : _xlsFile.GetCellValue(indexSheet, splitchart.Top, splitchart.Left, ref XF).ToString();
                    }
                    if (listsplitchart != null && listsplitchart.IsOneCell)
                    {
                        listsplit = _xlsFile.GetCellValue(indexSheet, listsplitchart.Top, listsplitchart.Left, ref XF) == null ? "" : _xlsFile.GetCellValue(indexSheet, listsplitchart.Top, listsplitchart.Left, ref XF).ToString();
                        if (listsplit != "")
                            rootchart = String.Format("*{0}*", listsplit.Split('*')[1]);
                    }
                    if (listsplit.Contains(inf.PositionReplace.Trim()))
                    {
                        if (split == "X")
                        {
                            if (inf.PositionReplace.Trim() == rootchart) // root chart
                            {
                                _codechart = String.Format("<div id=\"{0}\"></div>", inf.PositionReplace.Trim().Replace("*", ""));
                                _codechart += "<script type=\"text/javascript\">";
                                _codechart += String.Format("var myChart = new FusionCharts( \"/FusionCharts/{0}.swf\", \"myChartId\", \"{1}\", \"{2}\", \"0\", \"1\" );", inf.ChartType.Trim(), inf.width, inf.height);
                                _codechart += String.Format("myChart.setXMLData(\"{0}\" );", _dataxml);
                                _codechart += String.Format("myChart.render(\"{0}\");", inf.PositionReplace.Trim().Replace("*", ""));
                                _codechart += "</script>";
                            }
                            else
                            {
                                _codechart = String.Format("<div id=\"{0}\"></div>", inf.PositionReplace.Trim().Replace("*", ""));
                                _codechart += "<script type=\"text/javascript\">";
                                _codechart += "FusionCharts(\"myChartId\").configureLink ({";
                                _codechart += String.Format("swfUrl : \"/FusionCharts/{0}.swf\",", inf.ChartType.Trim());
                                _codechart += String.Format("renderAt : \"{0}\",", inf.PositionReplace.Trim().Replace("*", ""));
                                _codechart += String.Format("width : \"{0}\",", inf.width);
                                _codechart += String.Format("height : \"{0}\"", inf.height);

                                String namechart = inf.PositionReplace.Trim().Replace("*", "");
                                int indexchart = int.Parse(namechart[namechart.Length - 1].ToString()) - 1;
                                _codechart += String.Format("}},{0});", indexchart);
                                _codechart += "</script>";
                            }
                        }
                    }
                    else
                    {
                        _codechart = FusionCharts.RenderChart(String.Format("/FusionCharts/{0}.swf", inf.ChartType.Trim()), "", _dataxml, "myNext", inf.width.ToString(), inf.height.ToString(), false, true);
                    }
                }
                else if (inf.ChartType.Trim() != "")
                {
                    FusionCharts.SetRenderer("javascript");
                    _codechart = FusionCharts.RenderChartHTML(String.Format("/FusionCharts/{0}.swf", inf.ChartType.Trim()), "", _dataxml, "myNext", inf.width.ToString(), inf.height.ToString(), false);
                    _codechart = _codechart.Insert(_codechart.IndexOf("<param") - 1, " <param name=\"WMode\" value=\"opaque\"/> "); //Transparent,opaque
                    _codechart = _codechart.Insert(_codechart.IndexOf("<embed") + 6, " wmode=\"opaque\" ");

                }
            }
            return _codechart;
        }
        public String GetXMLLinkChart(ExcelFile _xlsFile, int indexsheet, string namerange, int x, int y, ref int XF, ref int icurr)
        {
            String kq = "";
            bool flag = false;
            TXlsNamedRange range = _xlsFile.GetNamedRange(namerange, indexsheet);
            if (range != null)
            {
                for (int i = y; i < range.RowCount - 1; i++)
                {
                    icurr = i;
                    string name = "";

                    name = _xlsFile.GetCellValue(indexsheet, range.Top + i, range.Left + x, ref XF) == null ? "" : _xlsFile.GetCellValue(indexsheet, range.Top + i, range.Left + x, ref XF).ToString();

                    string value = "";
                    value = _xlsFile.GetCellValue(indexsheet, range.Top + i, range.Left + x + 1, ref XF) == null ? "" : _xlsFile.GetCellValue(indexsheet, range.Top + i, range.Left + x + 1, ref XF).ToString();
                    if (name == "" && value != "")
                    {
                        name = _xlsFile.GetCellValue(indexsheet, range.Top + i - 1, range.Left + x, ref XF) == null ? "" : _xlsFile.GetCellValue(indexsheet, range.Top + i - 1, range.Left + x, ref XF).ToString();

                        kq += String.Format(" <linkeddata id='{0}Quarters'> ", name);
                        kq += "<chart>";
                        string attribute = "";
                        attribute += " formatNumberScale='0' ";
                        attribute += String.Format(" caption='{0}'", name);
                        TXlsNamedRange rangValue = _xlsFile.GetNamedRange("value", indexsheet);
                        String boolvalue = "";
                        if (rangValue != null && rangValue.IsOneCell)
                        {
                            boolvalue = _xlsFile.GetCellValue(indexsheet, rangValue.Top, rangValue.Left, ref XF) == null ? "" : _xlsFile.GetCellValue(indexsheet, rangValue.Top, rangValue.Left, ref XF).ToString();
                        }
                        if (boolvalue != "X")
                        {
                            attribute += " showValues='0' ";
                        }
                        string namex = _xlsFile.GetCellValue(indexsheet, range.Top + i, range.Left + x + 1, ref XF) == null ? "" : _xlsFile.GetCellValue(indexsheet, range.Top + i, range.Left + x + 1, ref XF).ToString();
                        string namey = _xlsFile.GetCellValue(indexsheet, range.Top + i, range.Left + x + 2, ref XF) == null ? "" : _xlsFile.GetCellValue(indexsheet, range.Top + i, range.Left + x + 2, ref XF).ToString();
                        attribute += String.Format(" xAxisName='{0}'", XmlEncoder.Decode(namex));
                        //        attribute += " useRoundEdges='1' ";

                        if (namey != "")
                            attribute += String.Format(" yAxisName='{0}'", XmlEncoder.Decode(namey));
                        //   namerange = namerange.Replace(namerange[namerange.Length - 3].ToString(), (int.Parse(namerange[namerange.Length - 3].ToString()) + 1).ToString());
                        kq += GetXMLLinkChart(_xlsFile, indexsheet, namerange, x + 1, i + 1, ref XF, ref icurr);
                        kq = kq.Insert(kq.IndexOf("<chart>") + 6, attribute);
                        kq += " </chart></linkeddata> ";

                        i = icurr;
                        name = _xlsFile.GetCellValue(indexsheet, range.Top + i, range.Left + x, ref XF) == null ? "" : _xlsFile.GetCellValue(indexsheet, range.Top + i, range.Left + x, ref XF).ToString();
                        value = _xlsFile.GetCellValue(indexsheet, range.Top + i, range.Left + x + 1, ref XF) == null ? "" : _xlsFile.GetCellValue(indexsheet, range.Top + i, range.Left + x + 1, ref XF).ToString();
                        if (name != "" && value != "")
                        {
                            i--;
                        }
                        else
                        {
                            flag = true;
                            //    kq = "<*>" + kq;
                            switch (x)
                            {
                                case 0:
                                    kq = ArraytoString(lv1) + kq;

                                    lv1.Clear();
                                    clv2.Clear();
                                    break;
                                case 1:
                                    kq = ArraytoString(lv2) + kq;

                                    lv2.Clear();
                                    clv2.Add(kq);
                                    break;

                            }
                            return kq;

                        }

                    }
                    else if (name != "" && value != "")
                    {
                        string link = "";
                        string nextname = _xlsFile.GetCellValue(indexsheet, range.Top + i + 1, range.Left + x, ref XF) == null ? "" : _xlsFile.GetCellValue(indexsheet, range.Top + i + 1, range.Left + x, ref XF).ToString();
                        string nextvalue = _xlsFile.GetCellValue(indexsheet, range.Top + i + 1, range.Left + x + 1, ref XF) == null ? "" : _xlsFile.GetCellValue(indexsheet, range.Top + i + 1, range.Left + x + 1, ref XF).ToString();
                        if (nextname == "" && nextvalue != "")
                        {
                            link = String.Format("link='newchart-xml-{0}Quarters'", name);
                            //        flag = true;
                        }
                        string temp = String.Format(" <set label ='{0}' value='{1}' {2} />", XmlEncoder.Decode(name), value, link);
                        //if (kq.IndexOf("<linkeddata") != -1)
                        //{
                        //    if (kq.IndexOf("<linkeddata") == 0)
                        //        kq = " " + kq;
                        //    kq = kq.Insert(kq.IndexOf("<linkeddata") - 1, temp);
                        //}
                        //else
                        //    kq += temp;
                        //if (!flag)
                        //    kq += temp;
                        //else
                        //    global += temp;
                        switch (x)
                        {
                            case 0:
                                lv1.Add(temp);
                                break;
                            case 1:
                                lv2.Add(temp);
                                break;
                            case 2:
                                lv3.Add(temp);
                                break;
                            case 3:
                                lv4.Add(temp);
                                break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                //if (flag)
                //    kq += "</linkeddata>";
            }
            switch (x)
            {
                case 0:
                    kq = ArraytoString(lv1) + ArraytoString(dlv1);
                    lv1.Clear();
                    dlv1.Clear();
                    break;
                case 1:
                    kq = ArraytoString(lv2) + ArraytoString(dlv2);
                    dlv2.Clear();
                    lv2.Clear();
                    break;
                case 2:
                    kq = ArraytoString(lv3) + ArraytoString(dlv3);
                    dlv3.Clear();
                    lv3.Clear();
                    break;
                case 3:
                    kq = ArraytoString(lv4) + ArraytoString(dlv4);
                    dlv4.Clear();
                    lv4.Clear();
                    break;
            }
            return kq;
        }
        protected static string ArraytoString(ArrayList list)
        {
            String kq = "";
            for (int i = 0; i < list.Count; i++)
            {
                kq += list[i] + " ";
            }
            return kq;
        }
        public static string StringToBase64(string str)
        {
            byte[] b = System.Text.Encoding.UTF8.GetBytes(str);
            string b64 = Convert.ToBase64String(b);
            return b64;
        }

        #endregion

        class clsParam
        {
            public clsParam()
            {
            }
            public clsParam(string strname, string strvalue)
            {
                name = strname;
                value = strvalue;
            }
            string name = "";

            public string Name
            {
                get { return name; }
                set { name = value; }
            }
            string value = "";

            public string Value
            {
                get { return value; }
                set { this.value = value; }
            }
        }



        public ExcelFile PrintExcel()
        {
            if (XlsPrint == null)
            {
                Report.ReportGenerator rg = null;
                DataSet ds = new DataSet();

                if (_info.ReportTmp != "" || _info.QDCode != "" || _info.ReportTmp_Print != "")
                {
                    String namereport = "";
                    if (_info.ReportTmp_Print != "")
                        namereport = "DB_" + _info.ReportTmp_Print;
                    else
                        if (_info.ReportTmp != "")
                            namereport = "DB_" + _info.ReportTmp;
                        else
                            namereport = _info.QDCode;
                    CoreCommonControl.SetConnection(MainForm.ReportConnectString);
                    try
                    {
                        if (_info.QDCode != "")
                        {
                            //         _info.ReportTmp = _info.QDCode;
                            SQLBuilder sqlBuilder = SQLBuilder.LoadSQLBuilderFromDataBase(_info.QDCode, MainForm.DB, "");
                            foreach (Filter f in sqlBuilder.Filters)
                            {
                                foreach (KeyValuePair<string, object> it in _params)
                                {
                                    f.ValueFrom = f.ValueFrom.Replace(String.Format("{{{0}}}", it.Key), it.Value.ToString());
                                    f.ValueTo = f.ValueTo.Replace(String.Format("{{{0}}}", it.Key), it.Value.ToString());
                                }
                            }
                            rg = new Report.ReportGenerator(sqlBuilder, namereport, "", MainForm.AppConnectString, MainForm.ServerPath + "ReportTemplate\\", MainForm.ServerPath + "Report\\", "");
                        }
                        else
                        {
                            rg = new Report.ReportGenerator(ds, namereport, MainForm.DB, MainForm.AppConnectString, MainForm.ServerPath + "ReportTemplate\\", MainForm.ServerPath + "Report\\", "");
                        }
                        rg.ValueList = _params;
                        XlsPrint = rg.CreateReport();
                    }
                    catch (Exception e)
                    {
                        sErr = e.Message;
                    }
                }

            }
            return XlsPrint;
        }

        public string LoadGadgetToString(string htmlHandle)
        {
            string namereport = "DB_" + _info.ReportTmp;
            if (Xls == null)
                Init();
            string content = Report.ReportGenerator.ExportHTML2String(_Path, Xls);// ExportHTML(_Path, namereport);
            // string content = "";

            content = content.Replace("{0}", htmlHandle);
            content = ReplaceCodeChart(content, _charts, Xls);
            try
            {
                return content;
            }
            catch (Exception e)
            {
                return e.Message;
            }

        }
    }
}
